import hashlib

DB_FILE_PATH = "utils/db.txt"


def md5(data_string):
    obj = hashlib.md5("asdfasdfasdfasdfa3exc".encode('utf-8'))
    obj.update(data_string.encode('utf-8'))
    return obj.hexdigest()


def register():
    # 1.输入
    user = input("输入用户名：")
    pwd = input("输入密码：")

    # 2.加密
    password = md5(pwd)

    # 3.写入文件
    with open(DB_FILE_PATH, mode='a', encoding='utf-8') as f:
        line = "{}|{}\n".format(user, password)
        f.write(line)


def login():
    user = input("用户名：")
    pwd = input("密码：")
    password = md5(pwd)

    is_success = False
    with open(DB_FILE_PATH, mode='r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            db_user, db_pwd = line.split('|')
            if db_user == user and db_pwd == password:
                is_success = True
                break

    if is_success:
        print("登录成功")
    else:
        print("登录失败")


def run():
    func_dict = {
        "1": register,
        "2": login
    }

    print("1.注册  2.登录")
    choice = input("序号：")
    func = func_dict.get(choice)
    if not func:
        print("输入错误")
    else:
        func()


if __name__ == '__main__':
    run()
